package com.hcy.authbusiness.service.impl;

import com.hcy.authmodel.domain.entity.User;
import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import com.hcy.userclient.client.UserAuthClient;
import com.hcy.usermodel.dto.request.UserAuthRequestDTO;
import com.hcy.usermodel.dto.response.UserAuthsResponseDTO;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by macro on 2019/9/30.
 */
@Service
public class UserService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserAuthClient userAuthClient;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //可在此做扩展
        UserAuthRequestDTO userAuthRequestDto = new UserAuthRequestDTO();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String businessCode = request.getHeader("business");
        if (StringUtils.isEmpty(businessCode)) {
            //分割穿过来的用户信息 注意用户名和业务标识中不能出现*
            String[] userInfo = username.split("\\+");
            if (userInfo.length != 2) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            username = userInfo[0];
            businessCode = userInfo[1];
        }
        logger.info("businessCode = [{}]", businessCode);
        userAuthRequestDto.setUsername(username);
        userAuthRequestDto.setBusinessCode(businessCode);
        ResponseData<UserAuthsResponseDTO> authsByName = userAuthClient.getAuthsByName(userAuthRequestDto);

        if (authsByName.getCode() == Code.Success) {
            UserAuthsResponseDTO data = authsByName.getData();
            if (data != null) {
                return new User(data.getUsername(), data.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(data.getAuthorities()));

            }
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
